import { Injectable, NotFoundException } from '@nestjs/common';
import { Express } from 'express';
import { join } from 'path';
import { ensureDir, writeFile } from 'fs-extra';
import { AddfoodsEntity } from '@src/modules/Food/entities/Addfoods.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from '@src/modules/User/User.entity';
@Injectable()
export class UploadService {
    private readonly uploadPath = join(process.cwd(), 'uploads');

    constructor(
        @InjectRepository(AddfoodsEntity)
        private readonly addfoodsRepository: Repository<AddfoodsEntity>,
        @InjectRepository(UserEntity)
        private readonly userRepository: Repository<UserEntity>
    ) {
        ensureDir(this.uploadPath);
    }

    async uploadFile(file: Express.Multer.File, foods_title: string, userId: string): Promise<AddfoodsEntity> {
        const user = await this.userRepository.findOne({ where: { id: userId } })
        console.log(user + "aaaaaaaaaaaaaaaaaaaaaaa")
        if (!user && user != userId) {
            throw new Error("用户id为空或不存在")
        } else {
            const filePath = join(this.uploadPath, file.originalname);
            await writeFile(filePath, file.buffer);
            const imageUrl = `http://www.localhost:4000/uploads/${file.originalname}`;
            const foods = new AddfoodsEntity()
            foods.foods_img = imageUrl;
            foods.foods_title = foods_title;
            foods.userId = userId


            return this.addfoodsRepository.save(foods)
        }

    }

    //修改新增菜品
    async updateFood(foodsId: string, foods_title: string, file: Express.Multer.File, userId: string): Promise<AddfoodsEntity> {
        const food = await this.addfoodsRepository.findOne({ where: { id: foodsId, userId } });
        console.log(userId)
        console.log(foodsId)
        if (!food) {
            throw new NotFoundException("菜品不存在或用户无权限修改");
        }

        if (file) {
            const filePath = join(this.uploadPath, file.originalname);
            await writeFile(filePath, file.buffer);
            food.foods_img = `http://www.localhost:4000/uploads/${file.originalname}`;
        }

        food.foods_title = foods_title;

        return this.addfoodsRepository.save(food);
    }

    //用户新增菜品列表
    async addlist(userId: any): Promise<AddfoodsEntity[]> {
        const addlist = await this.addfoodsRepository.find({
            where: { userId }
        });
        if (!addlist) {
            throw new NotFoundException("userId不存在");
        }
        return addlist;
    }

    //根据id查询菜品
    async addlistid(id: any): Promise<AddfoodsEntity[]> {
        return await this.addfoodsRepository.find({
            where: { id }
        })
    }

    //删除菜品
    async deleteaddlist(id: string, userId: string): Promise<any> {
        return await this.addfoodsRepository.delete({ id, userId })
    }
}
